package com.cccyy.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class HttpClientExample {

    private static final int MAX_RETRIES = 3;
    private static final int TIMEOUT = 30000; // 30 seconds
    private static final Logger log = LoggerFactory.getLogger(HttpClientExample.class);

    public static void main(String[] args) {
        String url = "http://example.com/api/endpoint"; // 替换为你的目标URL
        String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}"; // JSON数据

        retryAndTimeout(url, json);

        justTimeout(url, json);
    }

    private static void retryAndTimeout(String url, String json) {
        try (CloseableHttpClient httpClient = createHttpClientWithTimeout()) {
            for (int retryCount = 0; retryCount < MAX_RETRIES; retryCount++) {
                try {
                    HttpPost httpPost = new HttpPost(url);
                    StringEntity entity = new StringEntity(json, "UTF-8");
                    entity.setContentType("application/json");
                    httpPost.setEntity(entity);

                    HttpResponse response = httpClient.execute(httpPost);
                    HttpEntity responseEntity = response.getEntity();
                    if (responseEntity != null) {
                        String responseBody = EntityUtils.toString(responseEntity, "UTF-8");
                        if (response.getStatusLine().getStatusCode() == 200) {
                            log.info("Request successful: {}", responseBody);
                            return; // 请求成功，退出循环
                        } else {
                            log.info("Request failed with status code: {}", response.getStatusLine().getStatusCode());
                        }
                    }
                } catch (IOException e) {
                    log.error("IOException occurred, retry count: {}", retryCount);
                    if (retryCount == MAX_RETRIES - 1) {
                        throw e; // 如果是最后一次重试，则抛出异常
                    }
                    // 否则等待一段时间后再重试（这里为了简化省略了等待逻辑）
                }
            }
            // 如果循环结束还没有成功，则可以考虑抛出异常或记录错误日志
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void justTimeout(String url, String json) {
        CloseableHttpClient httpClient = createHttpClientWithTimeout();
        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity entity = new StringEntity(json, "UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                log.info("Response content: {}", EntityUtils.toString(responseEntity, "UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static CloseableHttpClient createHttpClientWithTimeout() {
        HttpClientBuilder builder = HttpClients.custom();
        // 设置请求超时和连接超时
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(TIMEOUT)
                .setConnectTimeout(TIMEOUT)
                .setConnectionRequestTimeout(TIMEOUT)
                .build();
        builder.setDefaultRequestConfig(requestConfig);

        return builder.build();
    }

}
